<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader :show-filter="false" :title="'生活模式'">
          <template #top-right>
            <AddButton @add="onAddItem" />
          </template>
        </TableHeader>
      </template>
      <template #default>
        <n-data-table
            :loading="table.tableLoading.value"
            :data="table.dataList.value as Array<object>"
            :columns="tableColumns"
            :row-key="rowKey"
            :row-props="rowProps"
            :pagination="false"
            :bordered="false"
            id="modelDragTable"
            handle="#handle-drag"

        />

        <n-dropdown
            placement="bottom-start"
            trigger="manual"
            :x="xRef"
            :y="yRef"
            :options="options"
            :show="showDropdownRef"
            :on-clickoutside="onClickoutside"
            @select="handleSelect"
        />
      </template>
    </TableBody>
    <ModalDialog ref="modalDialogRef" @confirm="onDataFormConfirm">
      <template #content>
        <DataForm ref="dataFormRef" :options="formItems" :form-config="formConfig"/>
      </template>
    </ModalDialog>
  </div>
</template>

<script lang="ts">
import Sortable from "sortablejs";
import {post, Response} from '@/api/http'
import {addLifeMode, changeLifeModeOrder, getLifeModeList, startLifeMode, getRoleList, login} from '@/api/url'
import {
  TableActionModel,
  useRenderAction,
  useRowKey,
  useTable,
  useTableColumn,
} from '@/hooks/table'
import { DataFormType, ModalDialogType, FormItem } from '@/types/components'
import {DataTableColumn, FormProps, NInput, TreeOption, useDialog, useMessage} from 'naive-ui'
import {defineComponent, h, nextTick, onMounted, ref, shallowReactive, watch} from 'vue'
import useUserStore from "@/store/modules/user";
import {UserState} from "@/store/types";
import {useRouter} from "vue-router";
import draggable from "vuedraggable";
import UseSurfaceSettingStore from "@/store/modules/surfaceSetting";
interface RowDataType {
  id:number
  name:string
  desc:string
  lifeModeItems:Array<number>
}

// 添加表单
const formItems = [
  {
    label: 'id',
    type: 'input',
    key: 'id',
    hidden:true,
    disabled:true,
    value: ref(null),
    render: (formItem) => {
      return h(NInput, {
        hidden:true,
        disabled:true,
        value: formItem.value.value,
        onUpdateValue: (val) => {
          formItem.value.value = val
        },
        placeholder: '请输入角色名称',
      })
    },
  },
  {
    label: '名称',
    type: 'input',
    key: 'name',
    value: ref(null),
    validator: (formItem, message) => {
      if (!formItem.value.value) {
        message.error('请输入角色名称')
        return false
      }
      return true
    },
    render: (formItem) => {
      return h(NInput, {
        value: formItem.value.value,
        onUpdateValue: (val) => {
          formItem.value.value = val
        },
        placeholder: '请输入角色名称',
      })
    },
  },
  {
    label: '描述',
    key: 'desc',
    value: ref(null),
    maxLength: 200,
    inputType: 'text',
    validator: (formItem, message) => {
      if (!formItem.value.value) {
        message.error('请输入角色名称')
        return false
      }
      return true
    },
    render: (formItem) => {
      return h(NInput, {
        value: formItem.value.value,
        onUpdateValue: (val) => {
          formItem.value.value = val
        },
        placeholder: '请输入角色描述',
        type: 'textarea',
        rows: 3,
      })
    },
  },
] as FormItem[]

export default defineComponent({
  name: 'lifeMode',
  components: {draggable},
  setup() {
    const userStore = useUserStore()
    const router = useRouter()
    const table = useTable<RowDataType>()
    const rowKey = useRowKey('id')
    const naiveDialog = useDialog()
    const message = useMessage()
    const useSurfaceSetting = UseSurfaceSettingStore()

    const formConfig = {
      labelWidth: 100,
      size: 'medium',
      labelAlign: 'right',
    } as FormProps

    // 表头
    const tableColumns = useTableColumn(
        [
          table.selectionColumn,
          // table.indexColumn,
          {
            title: 'id',
            key: 'id',
            resizable: true,
          },
          {
            title: '名字',
            key: 'name',
            resizable: true,
          },
          {
            title: '描述',
            key: 'desc',
            resizable: true,
          },
          {
            title: '操作',
            key: 'actions',
            render: (rowData) => {
              let type = 'default'
              if(rowData.id === useSurfaceSetting.getSurfaceSetting().onLifeModeId)
                type = 'error';
              return useRenderAction([
                {
                  label: '上下移动',
                  type:type,
                  // onClick: onUpdateItem.bind(null, rowData),
                  id: "handle-drag"
                }
              ] as TableActionModel[])
            },
          },
        ],
        {
          align: 'center',
        } as DataTableColumn
    )

    // 添加/编辑框
    let toAdd = 0;
    const modalDialogRef = ref<ModalDialogType | null>(null)
    const dataFormRef = ref<DataFormType | null>(null)
    async function onDataFormConfirm() {
      if (dataFormRef.value?.validator()) {
        modalDialogRef.value?.toggle()
        const params = {...dataFormRef.value.generatorParams(), toAdd:toAdd}
        // console.log(params)
        try {
          table.tableLoading.value = true;
          const data: Response = await post({
            url: addLifeMode,
            data: params,
            token:userStore.getToken()
          });
          // console.log(data)
          message.success(data.msg)
        }catch(e) {
          message.error((e as Error).message)
        }finally {
          table.tableLoading.value = false;
        }
      }
    }

    // 下拉菜单
    let chooseRow:RowDataType|null = null;
    const options = [
      {
        label: "选择生活",
        key: "live",
      },
      {
        label: "查看",
        key: "show",
      },
      {
        label: "编辑",
        key: "edit",
      },
      {
        label: () => h("span", { style: { color: "red" } }, "删除"),
        key: "delete",
      },
    ];
    const showDropdownRef = ref(false);
    const xRef = ref(0);
    const yRef = ref(0);
    const onClickoutside = () => {
      showDropdownRef.value = false;
    };
    const handleSelect = (key: string, node: string) => {
      // console.log(key, node);
      showDropdownRef.value = false;
      if (key == "edit") {
        onUpdateItem(chooseRow)
      }
      if (key == "delete") {
        onDeleteItem(chooseRow)
      }
      if (key == "show") {
        onShow(chooseRow)
      }
      if (key == "live") {
        onLive(chooseRow)
      }
    };
    const rowProps = (row:RowDataType) => {
      return {
        // 双击
        ondblclick: (e: MouseEvent) => {
          e.preventDefault()
          // message.info(JSON.stringify(row, null, 2));
          showDropdownRef.value = true;
          xRef.value = e.clientX;
          yRef.value = e.clientY;
          // console.log('rowProps',row)
          chooseRow = row
        },
        onContextmenu: (e: MouseEvent) => {
          e.preventDefault()
          // message.info(JSON.stringify(row, null, 2));
          showDropdownRef.value = true;
          xRef.value = e.clientX;
          yRef.value = e.clientY;
          // console.log('rowProps',row)
          chooseRow = row
        },
      };
    };

    // 操作
    function onShow(params: RowDataType|null){
      if(params){
        useSurfaceSetting.getSurfaceSetting().showLifeModeId = params.id;
      }
    }
    function onLive(params: RowDataType|null){
      if(params){
        const func = async (id:number,beginTime:number, endTime:number|null) => {
          try {
            const data : Response = await post({
              url: startLifeMode,
              data: {id:id,beginTime:beginTime,endTime:endTime},
              token:userStore.getToken()
            });
            // console.log(data)
            useSurfaceSetting.getSurfaceSetting().onLifeModeId = params.id
            useSurfaceSetting.getSurfaceSetting().onLifeModeLastBeginTime = beginTime;
            message.success(data.msg)
          }catch(e) {
            message.error((e as Error).message)
          }finally {
          }
        }
        naiveDialog.warning({
          title: '提示',
          content: '是否要选择该模式生活？',
          positiveText: '记录上一段的时间',
          negativeText: '取消上一段的时间',
          onNegativeClick:()=>{
            func(params.id,new Date().getTime(),null)
          },
          onPositiveClick:() => {
            func(params.id,new Date().getTime(),new Date().getTime())
          },
        })
      }
    }
    function onAddItem() {
      toAdd = 0;
      modalDialogRef.value?.toggle()
      nextTick(() => {
        dataFormRef.value?.reset()
      })
    }
    function onUpdateItem(item: any) {
      // console.log(item)
      toAdd = 1;
      modalDialogRef.value?.toggle()
      nextTick(() => {
        formItems.forEach((it) => {
          const key = it.key
          const propName = item[key]
          // console.log(item[key])
          if (propName) {
            it.value.value = propName
          }
        })
      })
    }
    function onDeleteItem(params: RowDataType|null) {
      toAdd = 2;
      naiveDialog.warning({
        title: '提示',
        content: '是否要删除？',
        positiveText: '删除',
        onPositiveClick:async () => {
          try {
            table.tableLoading.value = true;
            const data : Response = await post({
              url: addLifeMode,
              data: {...params,toAdd:toAdd},
              token:userStore.getToken()
            });
            // console.log(data)
            message.success(data.msg)
          }catch(e) {
            message.error((e as Error).message)
          }finally {
            table.tableLoading.value = false;
          }
        },
      })
    }
    // 移动
    function setSort() {
      /* 阻止火狐浏览器在  vue-draggable组件时拖动 打开新窗口 */
      document.body.ondrop = function(event) {
        event.preventDefault();
        event.stopPropagation();
      };

      let el = document.querySelector("#modelDragTable table tbody");
      // console.log('el',el);
      if(el)
        new Sortable(el as any, {
          handle: "#handle-drag",
          sort: true,
          ghostClass: "sortable-ghost",
          preventOnFilter: false,
          onEnd: async function (/**Event*/ e: any) {
            const list = table.dataList.value?.map(l=>l.id);
            if(list){
              const targetRow = list.splice(e.oldIndex, 1)[0];
              list.splice(e.newIndex, 0, targetRow);
              // console.log(list)
              try {
                table.tableLoading.value = true;
                const data : Response = await post({
                  url: changeLifeModeOrder,
                  data: {ids:list},
                  token:userStore.getToken()
                });
                // console.log(data)
                message.success(data.msg)
              }catch(e) {
                message.error((e as Error).message)
              }finally {
                table.tableLoading.value = false;
              }
            }
            // console.log(e)
            // e.preventDefault()
          },
        });
    }

    // 加载数据
    function doRefresh() {
      post<Array<RowDataType>>({
        url: getLifeModeList,
        data: {},
        token:userStore.getToken()
      }).then(async (res: Response) => {
        await table.handleSuccess({data:res.data.data})
        setSort()
      }).catch(console.log)

    }
    onMounted(doRefresh)
    watch(table.tableLoading,()=>{
      if(!table.tableLoading.value){
        doRefresh()
      }
    })

    return {
      showDropdownRef, xRef,yRef,options,handleSelect,rowProps,onClickoutside,
      modalDialogRef,
      dataFormRef,
      rowKey,
      tableColumns,
      formConfig,
      formItems,
      table,
      onAddItem,
      onDataFormConfirm,
    }
  },
})
</script>
